<?php

namespace App\Listeners;

use App\Events\ReplaceOrInsertPostLatestMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\Message;
use App\Models\User;
use App\Http\Resources\LatestMessageResource;

class NotificationReplaceOrInsertPostLatestMessage
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ReplaceOrInsertPostLatestMessage  $event
     * @return void
     */
    public function handle(ReplaceOrInsertPostLatestMessage $event)
    {
        $latestMessage = $event->latestMessage;
        $message = Message::where('to_id', $latestMessage->group_id)->where('type', 'group')->where('message_type', 'post')->latest('created_at')->first();//找到朋友圈的文章

        if($message){
            $postUser = User::find($message->from_id);

            if($postUser){
                $friendUGroupIds = $postUser->getFriendGroupIds();
                foreach ($friendUGroupIds as $friendUGroupId){
                    app('gateway')->sendToGroup($friendUGroupId,[
                        'type'=>'replace_or_insert_latest_message',
                        'content' => new LatestMessageResource($latestMessage)
                    ],null,'im_replace_or_insert_latest_message');
                }   
            }else{
                \Log::info('ReplaceOrInsertLatestMessage:',[
                    'code' => 1,
                    'msg' =>'找不到发布朋友圈的用户',
                    'data' =>[
                        'event' => 'ReplaceOrInsertLatestMessage',
                        'latest_message' => $latestMessage->id,
                    ],
                ]);
            }
        }else{
            \Log::info('ReplaceOrInsertLatestMessage:',[
                'code' => 1,
                'msg' =>'找不到发布的朋友圈',
                'data' =>[
                    'event' => 'ReplaceOrInsertLatestMessage',
                    'latest_message' => $latestMessage->id,
                ],
            ]);
        }
    }
}
